import type { HmrContext, Plugin, UserConfig, ViteDevServer } from "vite";
import { Parser } from "./parser";
import { Declaration } from "./parser/declaration";
import type { Options } from "./typing";

interface VueQuery {
  vue?: boolean
  src?: boolean
  type?: 'script' | 'template' | 'style' | 'custom'
  index?: number
  lang?: string
}

const VitePluginVueDialog =(options:Options ={dirs:"src/components"}):Plugin =>{
  const opt = options ?? {};
  let parser:Parser;
  let declaration:Declaration;
  
  declaration = new Declaration("/"+opt.dirs)

  return {
    name:"vite-pligin-vue-dialog",
    enforce:"pre",

    async configResolved(_conifg){
      declaration.create()
      declaration.updatedts()
    },
    handleHotUpdate(ctx:HmrContext){
      const visable = declaration.visable(ctx.file);     
      if(visable) declaration.updatedts()
    },
    async transform(code: string, id: string){

      if(/\.vue$/.test(id) || /\.vue\?.*type=script.*/.test(id)){

        parser = new Parser(code);

        if(!parser.unimport) await parser.createUnImport(declaration.path);

        await parser.isUnImport();

        if(!parser.isImport){
          return null
        }

        parser.parseCode(code);

        const importCode = parser.importMoundle(parser.autoAddImport);

        const s = parser.transformer(code,importCode);
        return s
      }
      
    },
  }
}

export { VitePluginVueDialog };

export default VitePluginVueDialog;